#!/bin/bash

if [ $# -lt 4 ]
then
    echo "usage: get_chips.sh Xmin Xmax Ymin Ymax [z=17]"
    exit
fi
Xmin=$1
Xmax=$2
Ymin=$3
Ymax=$4

if [ $# -lt 5 ]
then
    z=17
else
    z=$5
fi

server="http://mt1.google.com/vt"
cache="./chip_cache"
ofname="output.png"
conf="output.txt"
echo "" > $conf

# create a place to store intermediate chips
mkdir -p $cache

# Loop over pixel ranges
for ((y=$Ymin ; y<=$Ymax; y++ ))
do
for ((x=$Xmin ; x<=$Xmax; x++ ))
do
    # server side file name
    file=$(echo "x=$x&y=$y&z=$z")
    # local file name
    fname="z${z}_y${y}_x${x}.png"

    # download the file if you don't have it already
    if [ ! -f $cache/$fname ]
    then
        echo "Downloading $fname to cache."
        wget -q $server/$file -O $cache/$fname
    fi

    echo $cache/$fname >> $conf
done
done

echo $ofname >> $conf

width=$(echo "1+$Xmax-$Xmin"|bc);

cat $conf | xargs montage -tile ${width}x -geometry 100%x100%+0+0
